/**
 * 网站主JS文件
 */

// 当文档加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化暗黑模式
    initDarkMode();
    
    // 初始化书籍上传区域（如果存在）
    initUploadArea();
    
    // 初始化拖拽排序（如果存在）
    initSortable();
    
    // 初始化工具提示
    initTooltips();
    
    // 点赞功能
    initLikeButtons();
});

/**
 * 初始化暗黑模式
 */
function initDarkMode() {
    const darkModeToggle = document.getElementById('darkModeToggle');
    
    if (!darkModeToggle) return;
    
    // 根据本地存储设置初始状态
    if (localStorage.getItem('darkMode') === 'enabled') {
        document.documentElement.setAttribute('data-bs-theme', 'dark');
        if (darkModeToggle.querySelector('i')) {
            darkModeToggle.querySelector('i').classList.remove('fa-moon');
            darkModeToggle.querySelector('i').classList.add('fa-sun');
        }
    } else {
        document.documentElement.setAttribute('data-bs-theme', 'light');
    }
    
    // 切换暗黑模式
    darkModeToggle.addEventListener('click', function() {
        if (document.documentElement.getAttribute('data-bs-theme') === 'dark') {
            document.documentElement.setAttribute('data-bs-theme', 'light');
            localStorage.setItem('darkMode', 'disabled');
            if (this.querySelector('i')) {
                this.querySelector('i').classList.remove('fa-sun');
                this.querySelector('i').classList.add('fa-moon');
            }
        } else {
            document.documentElement.setAttribute('data-bs-theme', 'dark');
            localStorage.setItem('darkMode', 'enabled');
            if (this.querySelector('i')) {
                this.querySelector('i').classList.remove('fa-moon');
                this.querySelector('i').classList.add('fa-sun');
            }
        }
    });
}

/**
 * 初始化上传区域
 */
function initUploadArea() {
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('bookFileInput');
    
    if (!uploadArea || !fileInput) return;
    
    uploadArea.addEventListener('click', function() {
        fileInput.click();
    });
    
    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        this.classList.add('border-primary');
    });
    
    uploadArea.addEventListener('dragleave', function() {
        this.classList.remove('border-primary');
    });
    
    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        this.classList.remove('border-primary');
        
        if (e.dataTransfer.files.length) {
            fileInput.files = e.dataTransfer.files;
            handleFileSelection(fileInput);
        }
    });
    
    fileInput.addEventListener('change', function() {
        handleFileSelection(this);
    });
}

/**
 * 处理文件选择
 */
function handleFileSelection(input) {
    const fileNameDisplay = document.getElementById('selectedFileName');
    const filePreview = document.getElementById('filePreview');
    
    if (!fileNameDisplay || !input.files.length) return;
    
    const file = input.files[0];
    fileNameDisplay.textContent = file.name;
    
    // 如果是PDF或EPUB，可以尝试提取封面
    if (file.type === 'application/pdf' || file.name.endsWith('.epub')) {
        // 这里仅作为示例，实际提取封面需要后端处理
        if (filePreview) {
            filePreview.innerHTML = '<div class="alert alert-info">正在处理您的文件，提取元数据...</div>';
        }
        
        // 模拟提交文件以获取元数据
        const formData = new FormData();
        formData.append('file', file);
        
        fetch('/api/book/extract-metadata', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 200) {
                // 自动填充表单
                if (data.data.title) document.getElementById('title').value = data.data.title;
                if (data.data.author) document.getElementById('author').value = data.data.author;
                if (data.data.isbn) document.getElementById('isbn').value = data.data.isbn;
                if (data.data.publisher) document.getElementById('publisher').value = data.data.publisher;
                if (data.data.pubYear) document.getElementById('pubYear').value = data.data.pubYear;
                
                // 显示封面预览
                if (filePreview && data.data.coverUrl) {
                    filePreview.innerHTML = `<img src="${data.data.coverUrl}" class="img-thumbnail" style="max-height: 200px;">`;
                }
            }
        })
        .catch(error => {
            console.error('Error:', error);
            if (filePreview) {
                filePreview.innerHTML = '<div class="alert alert-warning">无法提取元数据，请手动填写信息。</div>';
            }
        });
    }
}

/**
 * 初始化Sortable.js拖拽排序
 */
function initSortable() {
    if (typeof Sortable !== 'undefined' && document.getElementById('sortableBookList')) {
        new Sortable(document.getElementById('sortableBookList'), {
            animation: 150,
            handle: '.drag-handle',
            onEnd: function(evt) {
                // 获取排序后的顺序
                const items = evt.to.querySelectorAll('[data-book-id]');
                const orderData = Array.from(items).map((item, index) => {
                    return {
                        bookId: item.dataset.bookId,
                        order: index + 1
                    };
                });
                
                // 发送到服务器更新顺序
                fetch(`/api/booklist/${document.getElementById('sortableBookList').dataset.listId}/reorder`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(orderData)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 200) {
                        showToast('顺序已更新', 'success');
                    } else {
                        showToast('顺序更新失败', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showToast('顺序更新失败', 'error');
                });
            }
        });
    }
}

/**
 * 初始化Bootstrap工具提示
 */
function initTooltips() {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}

/**
 * 初始化点赞按钮
 */
function initLikeButtons() {
    document.querySelectorAll('.like-button').forEach(button => {
        button.addEventListener('click', function() {
            const commentId = this.dataset.commentId;
            const likeCount = this.querySelector('.like-count');
            const icon = this.querySelector('i');
            
            // 切换点赞状态
            if (this.classList.contains('liked')) {
                this.classList.remove('liked');
                icon.classList.remove('fas');
                icon.classList.add('far');
                likeCount.textContent = parseInt(likeCount.textContent) - 1;
            } else {
                this.classList.add('liked');
                icon.classList.remove('far');
                icon.classList.add('fas');
                likeCount.textContent = parseInt(likeCount.textContent) + 1;
                
                // 添加点赞动画
                this.querySelector('i').classList.add('animate__animated', 'animate__heartBeat');
                setTimeout(() => {
                    this.querySelector('i').classList.remove('animate__animated', 'animate__heartBeat');
                }, 1000);
            }
            
            // 发送请求到服务器
            fetch(`/api/comment/${commentId}/like`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .catch(error => console.error('Error:', error));
        });
    });
}

/**
 * 显示提示消息
 */
function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type === 'error' ? 'danger' : type} border-0`;
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');
    
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">
                ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
    `;
    
    const toastContainer = document.querySelector('.toast-container');
    if (!toastContainer) {
        const container = document.createElement('div');
        container.className = 'toast-container position-fixed bottom-0 end-0 p-3';
        document.body.appendChild(container);
        container.appendChild(toast);
    } else {
        toastContainer.appendChild(toast);
    }
    
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
} 